package org.jeecg.modules.yw.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import org.jeecg.modules.yw.result.Result;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(tags = "文件上传")
@RequestMapping("/app/file")
public class FileController {
	/**
     * 时间格式化
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd/");

    /**
     * 图片保存路径，自动从yml文件中获取数据
     *   示例： E:/images/
     */
    @Value("${jeecg.path.upload}")
    private String fileSavePath;

    @PostMapping("upload")
    @ApiOperation(value = "文件上传")
    public Result uploadFile(MultipartFile file, HttpServletRequest request) {
        //后半段目录：  2020/03/15
        String directory = simpleDateFormat.format(new Date());
        /**
         * 文件保存目录  E:/images/2020/03/15/
         * 如果目录不存在，则创建
         */
        File dir = new File(fileSavePath+"/images/" + directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        System.out.println("图片上传，保存位置：" + fileSavePath+"/images/"+ directory);
        //给文件重新设置一个名字
        //后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName= UUID.randomUUID().toString().replaceAll("-", "")+suffix;
        //创建这个新文件
        File newFile = new File(fileSavePath+"/images/" + directory + newFileName);
        Result result = new Result();
        //复制操作
        try {
            file.transferTo(newFile);
            //协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
           // String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + directory + newFileName;
            String url = "/images/" + directory + newFileName;            
            System.out.println("图片上传，访问URL：" + url);
            result.setCode(0);
            result.setData(url);
            result.setMsg("上传成功!");           
            return result;
        } catch (IOException e) {
        	  result.setCode(0);
              result.setMsg("上传失败!");           
              return result;
        }
    }
}
